package com.hj.javaweb.util;

import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;

public class RedisTemplateUtil {
    private final String url = "127.0.0.1";
    private final int port = 6379;
    private final int database = 0;
    private final String password = "";;
    private final int timeout = 3000;// 连接超时时间-3秒

    // 初始化 RedisTemplate（核心：绑定连接工厂）
    public RedisTemplate<String,String> initRedisTemplate(){
        // 1.配置redis
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName(url);
        redisConfig.setPort(port);
        redisConfig.setDatabase(database);
        if (!password.isEmpty()){
            redisConfig.setPassword(password);
        }
        
        // 2.创建连接工厂（使用Lettuce客户端，spring推荐）
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfig);
        connectionFactory.setTimeout(timeout);
        connectionFactory.afterPropertiesSet();
        
        // 3.配置RedisTemplate
        RedisTemplate<String,String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);// 绑定连接工厂
        // 添加字符串序列化
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);

        redisTemplate.afterPropertiesSet();//初始化RedisTemplate
        return redisTemplate;
    }

    public static void main(String[] args) {
        RedisTemplateUtil util = new RedisTemplateUtil();
        RedisTemplate<String, String> redisTemplate = util.initRedisTemplate();
        try {
            redisTemplate.opsForValue().set("1","这是第1条测试数据",3, TimeUnit.MINUTES);
            // 获取数据
            String value = redisTemplate.opsForValue().get("1");
            System.out.println("获取redis数据："+value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
}
